//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');

Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    fileServerPath: app.globalData.fileServerPath,
    swiperCurrent: 0,  
    hasMoreSelect:false,
    goodsDetail: {},
    shopNum:0,
    hideShopPopup:true,
    addTotalPrice:0,
    buyNumber:0,
    buyNumMin:1,
    buyNumMax:0,
    canSubmit:false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo:{},
    shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
  },

  //事件处理函数
  swiperchange: function(e) {
       this.setData({  
        swiperCurrent: e.detail.current  
    })
  },

  onLoad: function (e) {
    var that = this;
    //商品详情
    wx.request({
      url: app.globalData.rootPath+'/m/goods/'+e.id,
      success: function(res) {
        if(res.data.meta.code === 200){
          res.data.data.goodsAttr_json = JSON.parse(res.data.data.goodsAttr_json)
          //将数据绑定到数据模板上
          that.setData({
            goodsDetail: res.data.data,
            pic_banner: res.data.data.pic_banner.split(","),
            buyNumMax: res.data.data.goods_number
          })
        }else{
        }
      }
      
    })
    that.getCartNum()
  },
  getCartNum:function(){
    var that = this;
    wx.request({
      url: app.globalData.rootPath + '/m/cart/count',
      data:{
        token: wx.getStorageSync("token")
      },
      success: function (res) {
        if (res.data.meta.code === 200) {
          //将数据绑定到数据模板上
          that.setData({
            shopNum: res.data.data
          })
        }
      }
    })
  },

  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },

  toAddShopCar: function (e) {
    if (e.target.dataset.buytype == "tobuy"){
      this.setData({
        shopType: "tobuy"
      })
    } 
    if (e.target.dataset.buytype == "addcart"){
      this.setData({
        shopType: "addShopCar"
      })
    }
  
    this.bindGuiGeTap();
  },
  tobuy: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },  
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    
     this.setData({  
        hideShopPopup: false 
    })  
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
     this.setData({  
        hideShopPopup: true 
    })  
  },
  //添加购物车的减法运算
  numJianTap: function() {
     //判断是否有规格
     if (this.data.goodsDetail.goodsAttr_json.length === 0) {
       //判断是否大于最小购买数量
       if (this.data.buyNumber > this.data.buyNumMin) {
         var currentNum = this.data.buyNumber;
         currentNum--;
         this.setData({
           buyNumber: currentNum,
           addTotalPrice: (this.data.goodsDetail.price * currentNum).toFixed(2)
         })
       }else{
         wx.showModal({
           title: '提示',
           content: '亲，多少买点吧！',
           showCancel: false
         })
       }
     } else if (this.data.goodsDetail.goodsAttr_json.length >= 0) {
       var msg = "";//提示信息
       var super_flag = true;
       var attrPrice = 0;//所选规格的增加价格
       for (var i = 0; i < this.data.goodsDetail.goodsAttr_json.length; i++) {
         var flag = false;
         for (var j = 0; j < this.data.goodsDetail.goodsAttr_json[i].goodsAttrList.length; j++) {
           if (this.data.goodsDetail.goodsAttr_json[i].goodsAttrList[j].active) {
             flag = true;
             attrPrice += this.data.goodsDetail.goodsAttr_json[i].goodsAttrList[j].increase_price
           }
         }
         if (!flag) {
           msg += this.data.goodsDetail.goodsAttr_json[i].attrName;//说明没有选择规格的规格名
         }
         super_flag = flag && super_flag;//判断是否选择了规格
       }
       if (super_flag) {
         //判断是否大于最小购买数量
         if (this.data.buyNumber > this.data.buyNumMin) {
           var currentNum = this.data.buyNumber;
           currentNum--;
           this.setData({
             buyNumber: currentNum,
             addTotalPrice: ((this.data.goodsDetail.price + attrPrice) * currentNum).toFixed(2)
           })
         } else {
           wx.showModal({
             title: '提示',
             content: '亲，多少买点吧！',
             showCancel: false
           })
         }
       } else {
         wx.showModal({
           title: '提示',
           content: '请选择' + msg,
           showCancel: false
         })
       }
     }
  },
  //添加购物车的加法运算
  numJiaTap: function() {
    //判断是否有规格
    if (this.data.goodsDetail.goodsAttr_json.length === 0){
      //判断是否小于库存数量
      if(this.data.buyNumber < this.data.buyNumMax){
        var currentNum = this.data.buyNumber;
        currentNum++ ;
        this.setData({  
            buyNumber: currentNum,
            addTotalPrice: (this.data.goodsDetail.price * currentNum).toFixed(2)
        })  
      }else{
       wx.showModal({
         title: '提示',
         content: '库存不足',
         showCancel: false
       })
      }
    } else if (this.data.goodsDetail.goodsAttr_json.length >= 0){
      var msg = "";//提示信息
      var super_flag = true;
      var attrPrice = 0;//所选规格的增加价格
      for (var i = 0; i < this.data.goodsDetail.goodsAttr_json.length ;i++){
        var flag = false;
        for (var j = 0; j < this.data.goodsDetail.goodsAttr_json[i].goodsAttrList.length; j++) {
          if (this.data.goodsDetail.goodsAttr_json[i].goodsAttrList[j].active){
            flag = true;
            attrPrice += this.data.goodsDetail.goodsAttr_json[i].goodsAttrList[j].increase_price
          }
        }
        if (!flag){
          msg += this.data.goodsDetail.goodsAttr_json[i].attrName;//说明没有选择规格的规格名
        }
        super_flag = flag && super_flag;//判断是否选择了规格
      }
      if(super_flag){
        if (this.data.buyNumber < this.data.buyNumMax) {
          var currentNum = this.data.buyNumber;
          currentNum++;
          this.setData({
            buyNumber: currentNum,
            addTotalPrice: ((this.data.goodsDetail.price + attrPrice) * currentNum).toFixed(2)
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '库存不足',
            showCancel: false
          })
        }
      }else{
        wx.showModal({
          title: '提示',
          content: '请选择' + msg,
          showCancel: false
        })
      }
    } 
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    var superindex = e.currentTarget.dataset.superindex;
    var index = e.currentTarget.dataset.index;

    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.goodsDetail.goodsAttr_json[superindex].goodsAttrList;
    for (var i = 0; i < childs.length; i++) {
      that.data.goodsDetail.goodsAttr_json[superindex].goodsAttrList[i].active = false;
    }
    // 设置当前选中状态
    that.data.goodsDetail.goodsAttr_json[superindex].goodsAttrList[index].active = true;
    // 获取所有的选中规格尺寸数据
    
    // 更新视图
    this.setData({
      goodsDetail: that.data.goodsDetail
    })  
  },

  setAttrInfo:function(){
    var goodsAttr_json = this.data.goodsDetail.goodsAttr_json;
    if(goodsAttr_json.length >= 0){
      var obj = {
        goods_attr: "",
        goods_attrs_id: "",
        goods_attrs_price:"",
      }
      for (var i = 0; i < goodsAttr_json.length; i++) {
        for (var j = 0; j < goodsAttr_json[i].goodsAttrList.length; j++) {
          if (goodsAttr_json[i].goodsAttrList[j].active) {
            if (obj.goods_attr == ""){
              obj.goods_attr += goodsAttr_json[i].goodsAttrList[j].attr_name
              obj.goods_attrs_id += goodsAttr_json[i].goodsAttrList[j].id
              obj.goods_attrs_price += goodsAttr_json[i].goodsAttrList[j].increase_price
            }else{
              obj.goods_attr = obj.goods_attr+","+goodsAttr_json[i].goodsAttrList[j].attr_name
              obj.goods_attrs_id = obj.goods_attrs_id + "," + goodsAttr_json[i].goodsAttrList[j].id
              obj.goods_attrs_price = obj.goods_attrs_price + "," + goodsAttr_json[i].goodsAttrList[j].increase_price
            }
          }
        }
      }
      return obj;
    }
  },
  /**
  * 加入购物车
  */
  addShopCar:function(){
    var that = this;

    if (that.data.addTotalPrice !== 0) {
      wx.request({
        url: app.globalData.rootPath + '/m/cart',
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data:{
          token: wx.getStorageSync("token"),
          goods_id: that.data.goodsDetail.id,
          goods_name: that.data.goodsDetail.goods_name,
          goods_price: that.data.goodsDetail.price,
          goods_number: that.data.buyNumber,
          goods_attr: that.setAttrInfo().goods_attr,
          goods_attrs_id: that.setAttrInfo().goods_attrs_id,
          goods_attrs_price: that.setAttrInfo().goods_attrs_price,
        },
        success: function (res) {
          if (res.data.meta.code === 200) {
            wx.showModal({
              title: '提示',
              content: '成功加入购物车',
              showCancel: false
            })
            that.setData({
              hideShopPopup: true
            })  
            that.getCartNum()
          } else {
            wx.showModal({
              title: '提示',
              content: '加入购物车失败--'+res.data.meta.message,
              showCancel: false
            })
          }
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel:false
      })
    }
  },
	
	
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.basicInfo.name,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.basicInfo.id,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },


  /**
  * 立即购买
  */
  buyNow: function () {

    if (this.data.addTotalPrice !== 0) {
      //组建立即购买信息
      var buyNowInfo = this.buliduBuyNowInfo();

      wx.setStorageSync('shopCarInfo', buyNowInfo);
      wx.setStorageSync('orderType', "buyNow");
      wx.navigateTo({
        url: "/pages/to-pay-order/index"
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
    }
  
  },
  /**
	 * 组建立即购买信息
	 */
  buliduBuyNowInfo: function () {
    var that = this;
    var data = [];
    if (that.data.addTotalPrice !== 0) {
      var gaplist = that.setAttrInfo().goods_attrs_price.split(",");
      var cp = 0;
      if (gaplist.length>0){
        for (var i = 0; i < gaplist.length; i++) {
          cp += parseFloat(gaplist[i]-0)
        }
      }
    
      data = [{
        goods_id: that.data.goodsDetail.id,
        goods_name: that.data.goodsDetail.goods_name,
        goods_price: (cp + parseFloat(that.data.goodsDetail.price)).toFixed(2),
        goods_img: that.data.goodsDetail.pic_main,
        goods_number: that.data.buyNumber,
        goods_attr: that.setAttrInfo().goods_attr,
        goods_attrs_id: that.setAttrInfo().goods_attrs_id,
        goods_attrs_price: that.setAttrInfo().goods_attrs_price,
      }]
    } else {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
    }
    return data;
  },   
  
})
